package com.xavier.config.handler;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.xavier.utils.UserContainer;
import com.xavier.vo.UserInfoVO;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * 自动填充字段
 */
@Component
public class XavierMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        UserInfoVO userInfoVO = UserContainer.get();
        if (ObjectUtil.isNotEmpty(userInfoVO)) {
            this.strictInsertFill(metaObject, "createUserId", Long.class, userInfoVO.getId());
            this.strictInsertFill(metaObject, "createNickName", String.class, userInfoVO.getNickName());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        UserInfoVO userInfoVO = UserContainer.get();
        if (ObjectUtil.isNotEmpty(userInfoVO)) {
            this.strictUpdateFill(metaObject, "updateUserId", Long.class, userInfoVO.getId());
            this.strictUpdateFill(metaObject, "updateNickName", String.class, userInfoVO.getNickName());
        }
    }

}
